package com.example.android.course.sample;

import com.example.android.course.sample.helpers.IOHelepr;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

    private static final String IS_USER_LOGGED_KEY = "isUserLogged";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        handleLogin();

    }

    private void navigateToMainActivity() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    private void handleLogin() {
        if (isUserLogged()) {
            navigateToMainActivity();
        } else {
            initListeners();
        }

    }

    private boolean isUserLogged() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        return prefs.getBoolean(IS_USER_LOGGED_KEY, false);
    }

    private void updateSharedPrefs() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        Editor editor = prefs.edit();
        editor.putBoolean(IS_USER_LOGGED_KEY, true);
        editor.commit();
    }

    private void initListeners() {
        findViewById(R.id.login_button).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                checkCredentials();
            }
        });

    }

    protected void checkCredentials() {
        Editable username = ((EditText) findViewById(R.id.login_username)).getText();
        Editable password = ((EditText) findViewById(R.id.login_password)).getText();
        IOHelepr ioHelepr = new IOHelepr();
        if (ioHelepr.areCredentialsCorrect(username.toString(), password.toString())) {
            updateSharedPrefs();
            navigateToMainActivity();
        } else {
            Toast.makeText(this, R.string.wrong_password, Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
